<?php
require_once "services/securityServices.php";

$securityServices = new SecurityService;

if(session_start()){
	if (isset($_SESSION['username'])){
		error_log("session: ".$_SESSION['username']);
	} else {

		if (isset($_REQUEST["mobile"])){

			if (isset($_REQUEST["username"]) && isset($_REQUEST["password"])){

				try {
					session_destroy();
					$securityServices->loginUser($_REQUEST["username"], $_REQUEST["password"]);
					$_SESSION['mobile'] = "true";

				}catch (Exception $e) {
					echo "<response>Invalid credentials</response>";
					exit;
				}

			} else {
				echo "<response>No username or password set.</response>";
				exit;
			}

		} else {
			header('Location: /index.html' );
		}
	}

	if (isset($_SESSION['userid'])){
		error_log("session: ".$_SESSION['userid']);
	} else {

		if (isset($_REQUEST["mobile"])){

			if (isset($_REQUEST["username"]) && isset($_REQUEST["password"])){

				try {

					$securityServices->loginUser($_REQUEST["username"], $_REQUEST["password"]);
				}catch (Exception $e) {
					echo "<response>Invalid credentials</response>";
					exit;
				}

			} else {
				echo "<response>No username or password set.</response>";
				exit;
			}

		} else {
			header('Location: /index.html' );
		}

	}

} else {

	if (isset($_REQUEST["mobile"])){
		echo "<response>No session started.</response>";
		exit;
	} else {
		header('Location: /index.html' );
	}

}

?>